package com.bysj.lms.Shiro;

import com.bysj.lms.pojo.entity.Permission;
import com.bysj.lms.pojo.entity.Role;
import com.bysj.lms.pojo.entity.User;
import com.bysj.lms.service.IPermissionService;
import com.bysj.lms.service.IRoleService;
import com.bysj.lms.service.IUserService;

import com.bysj.lms.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;



public class PasswordRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(PasswordRealm.class);

    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;

    @Autowired
    IPermissionService permissionService;

    /**
     * 用户授权
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //获取当前登录用户的账号

        String account = JwtUtil.getAccount((String)principal.getPrimaryPrincipal());
        logger.info("========="+principal.getPrimaryPrincipal());
        logger.info("=====1当前用户："+account);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(StringUtils.isNotBlank(account) && StringUtils.isNotEmpty(account)){
            //查询该用户的所有角色和权限
            //查找角色
            List<Role> roles = roleService.getByUsername(account);
            roles.forEach(role -> {if(role != null) info.addRole(role.getName());});
            logger.info("======1角色："+roles.toString());
            List<Permission> permissions = permissionService.getByRoleId(roles);
            logger.info("======1权限："+permissions.toString());
            permissions.forEach(permission -> {if(permission!=null) info.addStringPermission(permission.getUrl());});
        }
        return info;
    }

    /**
     * 用户身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        User user = userService.getByUsername(account);
        if(user == null){
            //抛出没找到账号异常
            throw new UnknownAccountException();
        //账号被锁定
        }else if(StringUtils.equals(user.getStatus(),"1")){
            //抛出账号被锁定异常
            throw new LockedAccountException();
        }
        String salt = user.getSalt();
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(account,user.getPassword(),getName());
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt));
        return simpleAuthenticationInfo;
    }
}
